package four;
import java.util.*;

public class A068 {



    //394.字符串解码




    //(1)数字（2）[ (3)] (4)字母
    Stack<Integer> stack1 = new Stack<>(); //存数字
    Stack<String> stack2 = new Stack<>(); //存字母，并且用来返回答案
    public String decodeString(String s) {

        char[] str = s.toCharArray();
        stack2.push("");
        int i=0;
        while(i<str.length) {
            if(str[i]<='9' && str[i]>='0') {
                StringBuilder sb = new StringBuilder();
                while(str[i]<='9' && str[i]>='0') {
                    sb.append(str[i++]);
                }
                stack1.push(Integer.parseInt(sb.toString()));
            }else if(str[i]=='[') {
                //存完整的字符串
                i++;
                StringBuilder sb = new StringBuilder();
                while(str[i]<='z' && str[i]>='a') {
                    sb.append(str[i++]);
                }
                stack2.push(sb.toString());
            } else if (str[i]==']') {
                //取出字符串，第一个字符串是要被重复的
                String rep = stack2.pop();
                String ret = stack2.pop();//前面加上""就是为了防止这种为空
                int count = stack1.pop();
                while(count != 0) {
                    ret += rep;
                    count--;
                }
                stack2.push(ret);
                i++;
            }else {
                //遇到字符，直接存入答案
                StringBuilder sb = new StringBuilder();
                while(i<str.length && str[i]<='z' && str[i]>='a') {
                    sb.append(str[i++]);
                }
                stack2.push(stack2.pop()+sb.toString());
            }
        }
        return stack2.pop();
    }

}
